package com.xxl.job.executor.utils;

import com.xxl.job.executor.dao.XxlJobLogDao;
import com.xxl.job.executor.model.XxlJobLog;
import com.xxl.job.executor.service.ScriptBase;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author xie xin
 * @date 2025/1/10 23:53
 */
@Component
public class ScriptUtil implements ApplicationRunner {
    @Resource
    private XxlJobLogDao xxlJobLogDao;

    public static ThreadPoolExecutor threadPool;
    @Override
    public void run(ApplicationArguments args) throws Exception {
        ThreadFactory namedThreadFactory = Executors.defaultThreadFactory();
        BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(10000);
        threadPool = new ThreadPoolExecutor(
                5, // corePoolSize
                20, // maximumPoolSize
                30, // keepAliveTime
                TimeUnit.SECONDS,
                workQueue,
                namedThreadFactory,
                new ThreadPoolExecutor.AbortPolicy()
        );

        Thread taskThread = new Thread(() -> {
            while (true) { // 使用while循环确保任务持续执行
                // 查询是否有未完成的脚本任务
                System.out.println("任务执行时间: " + System.currentTimeMillis());
                try {

                    // 等待10
                    Thread.sleep(10  * 1000);
                } catch (InterruptedException e) {
                    // 如果线程被中断，则退出循环（可选的退出机制）
                    System.out.println("线程被中断，任务停止执行");
                }
            }
        });

        taskThread.start(); // 启动线程
    }

    private void executeScript(){
        //待执行的脚本
        List<XxlJobLog> xxlJobLogList = xxlJobLogDao.queryNeedExecuteScript();
        for (XxlJobLog xxlJobLog : xxlJobLogList) {
            try {
                threadPool.execute(ScriptBase.getScript(xxlJobLog));
            } catch (Exception e){
                xxlJobLog.setHandleTime(new Date());
                xxlJobLog.setHandleCode(500);
                xxlJobLog.setHandleMsg(e.getMessage());
                xxlJobLogDao.updateHandleInfo(xxlJobLog);
            }
        }
    }
}
